import axios from 'axios'
import { Message } from 'element-ui'
import store from '@/store'
import router from '@/router'
import { getToken } from '@/utils/auth'
import qs from 'querystring'

// 创建axios实例
const service = axios.create({
  baseURL: process.env.VUE_APP_BASE_API || 'http://101.37.38.67:7001',
  timeout: 10000
})

// 请求拦截器
service.interceptors.request.use(
  config => {
    if (store.getters.token) {
      config.headers['Authorization'] = getToken()
    }
    return config
  },
  error => {
    console.log(error)
    return Promise.reject(error)
  }
)

// 响应拦截器
service.interceptors.response.use(
  response => {
    const res = response.data
    if (res.status !== 200) {
      if (res.status === 500) {
        Message({ message: res.message, type: 'error', duration: 5 * 1000 })
      }
      if (res.status === 401) {
        logout()
      }
      return Promise.reject(new Error(res.message || 'Error'))
    }
    return res
  },
  error => {
    console.log('err' + error)
    Message({
      message: error.message,
      type: 'error',
      duration: 5 * 1000
    })
    return Promise.reject(error)
  }
)

// 封装GET请求
export function get(url, params) {
  return service({
    url,
    method: 'get',
    params,
    headers: {
      'X-Requested-With': 'XMLHttpRequest'
    }
  })
}

// 封装DELETE请求
export function del(url, params) {
  return service({
    url,
    method: 'delete',
    params,
    headers: {
      'X-Requested-With': 'XMLHttpRequest'
    }
  })
}

// 封装POST请求（表单格式）
export function post(url, data) {
  return service({
    url,
    method: 'post',
    data: qs.stringify(data),
    headers: {
      'X-Requested-With': 'XMLHttpRequest',
      'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8'
    }
  })
}

// 封装POST请求（JSON格式）
export function postJSON(url, data) {
  return service({
    url,
    method: 'post',
    data,
    headers: {
      'X-Requested-With': 'XMLHttpRequest',
      'Content-Type': 'application/json'
    }
  })
}

// 封装PUT请求（表单格式）
export function put(url, data) {
  return service({
    url,
    method: 'put',
    data: qs.stringify(data),
    headers: {
      'X-Requested-With': 'XMLHttpRequest',
      'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8'
    }
  })
}

// 封装PUT请求（JSON格式）
export function putJSON(url, data) {
  return service({
    url,
    method: 'put',
    data,
    headers: {
      'X-Requested-With': 'XMLHttpRequest',
      'Content-Type': 'application/json'
    }
  })
}

// 退出登录
async function logout() {
  await store.dispatch('user/logout')
  router.push('/login')
}

export default service